import 'package:sqflite/sqflite.dart';
import '../entity/user.dart';
import 'database_helper.dart';

class UserRepository {
  final dbHelper = DatabaseHelper.instance;

  //插入新用户（注册）
  Future<void> insert(User user) async {
    final db = await dbHelper.database;
    await db.insert(
      'users',
      user.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace, //如果ID冲突则替换
    );
  }

  //根据登录账号查找用户（登录）
  Future<User?> getUserByAccount(String account) async {
    final db = await dbHelper.database;
    final maps = await db.query(
      'users',
      where: 'account = ?',
      whereArgs: [account],
    );

    if (maps.isNotEmpty) {
      return User.fromMap(maps.first);
    }
    return null;
  }

  //根据ID查找用户
  Future<User?> getUserById(String userId) async {
    final db = await dbHelper.database;
    final maps = await db.query(
      'users',
      where: 'id = ?',
      whereArgs: [userId],
    );

    if (maps.isNotEmpty) {
      return User.fromMap(maps.first);
    }
    return null;
  }
}